package com.zh.media.ui.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.zh.media.R;
import com.zh.media.ui.MainActivity;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "LoginActivitym";
    private EditText usernameEditText;
        private EditText passwordEditText;
        private Button loginButton;

        private String user = "admin";  //用户名
        private String psw = "666666";   //密码
        private String username, password;
        private  OkHttpClient client = new OkHttpClient();
        private SharedPreferences sharedPreferences;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            usernameEditText = findViewById(R.id.username);
            passwordEditText = findViewById(R.id.password);
            loginButton = findViewById(R.id.login);


            initEditText();

            loginButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new LoginTask().execute(username, password);
                }
            });

            // 读取数据,已經登錄就跳轉
            sharedPreferences = getSharedPreferences("MyInfo", MODE_PRIVATE);
            if(sharedPreferences.getBoolean("isLogin", false)){
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }

        }

        /**
         * @describetion 初始化輸入框
         * @author mark
         * @param
         * @param
         * @return
        */
    private void initEditText() {
        usernameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本改变之前的处理
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本正在改变的处理
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 文本改变之后的处理
                username = usernameEditText.getText().toString();
                if (!TextUtils.isEmpty(username) &&
                        !TextUtils.isEmpty(password) && password.length() >= 6){
                    loginButton.setEnabled(true);
                }
            }
        });
        passwordEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本改变之前的处理
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本正在改变的处理
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 文本改变之后的处理
                password = passwordEditText.getText().toString();
                if (!TextUtils.isEmpty(username) &&
                        !TextUtils.isEmpty(password) && password.length() >= 6){
                    loginButton.setEnabled(true);
                }
            }
        });
    }

    /**
          * @description 存储用户信息
          * @date: 2024/11/10 10:56
          * @author: mark
          * @param
          * @return
          */
    private void saveUserInfo(String userName, String password, boolean loginstatus) {
        // 获取SharedPreferences对象
        SharedPreferences sharedPreferences = getSharedPreferences("MyInfo", MODE_PRIVATE);

        // 使用SharedPreferences.Editor添加数据
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("userName", userName);
        editor.putString("password", password);
        editor.putBoolean("isLogin", loginstatus);
        // 提交保存
        editor.apply();

    }

    private class LoginTask extends AsyncTask<String, Void, Boolean> {

            @Override
            protected Boolean doInBackground(String... params) {
                String username = params[0];
                String password = params[1];
                // 这里使用网络请求来进行登录验证，可以使用Volley, Retrofit等库
                // 假设我们使用一个简单的方法来模拟登录验证
                //login(username, password);
                try {
                    Thread.sleep(2000);  // 模拟网络延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return user.equals(username) && psw.equals(password);
            }

            @Override
            protected void onPostExecute(Boolean success) {
                if (success) {
                    // 登录成功，跳转到主界面
                    saveUserInfo(username,password,true);
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                } else {
                    // 登录失败，显示错误信息
                    Toast.makeText(LoginActivity.this, "登录失败，请检查用户名和密码", Toast.LENGTH_SHORT).show();
                }
            }
        }


    private void login(String username,String password) {

        RequestBody formBody = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();

        Request request = new Request.Builder()
                .url("http://example.com/login")
                .post(formBody)
                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {


            @Override
            public void onFailure(okhttp3.Call call, final IOException e) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "Login Failed: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(okhttp3.Call call, final Response response) throws IOException {
                if (!response.isSuccessful()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "Login Failed: " + response.code(), Toast.LENGTH_LONG).show();
                        }
                    });
                    return;
                }

                final String responseData = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Handle login success or failure here
                        Toast.makeText(LoginActivity.this, "Login Response: " + responseData, Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

   private String  getInfo (String url){
    return null;
   }

    private String  login2 (String username,String password,String url){
        return null;
    }



    /**
     * OkHttp 同步 Get 请求
     */
    private void httpSynchronousGet() {
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .get()                          // 使用 Get 方法
                .build();

        // 同步 Get 请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                String result = null;
                try {
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    /**
     * OkHttp 异步 Get 请求
     */
    private void httpAsynchronousGet() {
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .get()                          // 使用 Get 方法
                .build();

        // 创建异步回调
        Callback callback = new Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                    }
                });
            }
        };

        // 异步 Get 请求
        client.newCall(request).enqueue(callback);
    }

    /**
     * OkHttp 同步 Post 请求
     */
    private void httpSynchronousPost() {
        // 创建 Post 表单 , 主要用于设置 Post 请求键值对
        FormBody formBody = new FormBody.Builder()
                .add("Key", "Value")
                .build();

        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .post(formBody)                 // 使用 Post 方法
                .build();

        // 同步 Get 请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                String result = null;
                try {
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    /**
     * OkHttp 异步 Post 请求
     */
    private void httpAsynchronousPost() {
        // 创建 Post 表单 , 主要用于设置 Post 请求键值对
        FormBody formBody = new FormBody.Builder()
                .add("Key", "Value")
                .build();

        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .post(formBody)                 // 使用 Post 方法
                .build();

        // 创建异步回调
        Callback callback = new Callback(){

            class TAG {
            }

            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                Log.i(TAG, "result : " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                    }
                });
            }
        };

        // 异步 Get 请求
        client.newCall(request).enqueue(callback);
    }



}

